import * as fs from 'node:fs/promises';
import { fetchDocDetail } from '../api/fetchDocDetail';
import * as configuration from '../configuration';
import { log } from '../helper/outputChannel';
import { Memory } from '../memory';
import { addUser } from './addUser';
import { fetchApiList } from './fetchApiList';
import { genApiTsfileByDocDetail } from './genApiTsFile';

export interface Arg0 {
  fsPath: string;
}

export async function refreshApi(arg0: Arg0) {
  const filePath = arg0.fsPath;
  const content = await fs.readFile(filePath).then(v => v.toString()).catch(e => console.log(e));
  const regResult = content?.match(/\/\/\/\/\s*@docId\s*(\S*)\n?/);
  if (!regResult || typeof regResult[1] !== 'string') { return; }
  const docId = regResult[1];

  log.show(true);
  let docItem = <Memory.IDoc | undefined>undefined;

  const users = await configuration.getUsers();
  if (!users.length) {
    log.warn('请先添加Torna用户');
    log.show();
    await addUser();
  }

  let docList = Memory.fullDocList.filter(v => v.url);
  if (!docList.length) {
    await fetchApiList();
  }

  docList = Memory.fullDocList.filter(v => v.url);
  if (!docList.length) {
    log.warn('接口文档列表为空');
    log.show();
    return;
  }

  docItem = docList.filter(v => v.id === docId)[0];
  if (!docItem) { return; }

  const detail = await fetchDocDetail(
    docItem.visitor.url + '/doc/view/detail',
    { authorization: docItem.visitor.token },
    { id: docItem.id }
  );
  return await genApiTsfileByDocDetail({
    detail,
    visitor: docItem.visitor
  });

}